package Servlet;

import DAO.CustomerDAO;
import DAO.DAOFactory;
import DAO.PackageDAO;
import javabean.Customer;
import javabean.CustomerPackage;
import javabean.Package;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.SQLException;

import static sun.text.normalizer.Utility.escape;

@WebServlet("/ChangePackage")
public class ChangePackageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PackageDAO packageDAO = (PackageDAO) DAOFactory.getPackageDAOInstance();
        HttpSession session = req.getSession();
        Customer customer = (Customer) session.getAttribute("loginCustomer"); // login user
        String selectedPackageId = req.getParameter("selectedPackage");
        System.out.println("selectedPackage" + selectedPackageId);
        System.out.println("customer" + customer.getCustomerID());
        if (selectedPackageId != null && !selectedPackageId.isEmpty()) {
            try {
                int packageID = Integer.parseInt(selectedPackageId);
                Package selectedPackage = packageDAO.SearchPackageByID(packageID);

                if(packageDAO.SubscribePackage(selectedPackage, customer)){
                    CustomerPackage customerPackage = packageDAO.GetCustomerPackage(customer);//获取当前用户的套餐信息
                    session.setAttribute("curPackage", customerPackage);
                    req.getRequestDispatcher("MyPackage.jsp").forward(req, resp);
                }else{
                    PrintWriter out = resp.getWriter();
                    out.println("<script>");
                    out.println("if(confirm('" + escape("您已订购该套餐，是否前往套餐订购页面？") + "')) {");
                    out.println("window.location.href='Subpackage';");
                    out.println("} else {");
                    out.println("  " + "window.location.href='Personal_Info.jsp';"); // 在这里添加重定向到个人信息页面的代码
                    out.println("}");
                    out.println("</script>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                resp.sendRedirect("index.jsp");
            }
        } else {
            // 未选择套餐，可以进行相应的处理，例如提示用户未选择套餐信息

            // 重定向到其他页面或返回响应给用户
            resp.sendRedirect("其他页面的URL");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
